import React, {useEffect, useState, useCallback} from 'react';
import {Button, Card, Col, message, Row, Select, Space, Statistic, Tag, Input} from 'antd';
import {AimOutlined, ExportOutlined, ReloadOutlined, SearchOutlined} from '@ant-design/icons';
import MapViewer from '../../components/MapViewer/MapViewer';
import DataTable from '../../components/DataTable/DataTable';
import {routesAPI, uploadDataAPI} from '../../services/api';
import {formatCurrency, formatTime} from '../../utils/formatters';
import {ROUTE_COLORS} from '../../utils/constants';

const {Option} = Select;
const RoutesPage = () => {
    const [routes, setRoutes] = useState([]);
    const [loading, setLoading] = useState(false);
    const [selectedRoute, setSelectedRoute] = useState(null);
    const [viewMode, setViewMode] = useState('map'); // 添加viewMode状态，默认为'map'
    const [dataId, setDataId] = useState('');
    const [batchList, setBatchList] = useState([]);
    const [statistics, setStatistics] = useState({
        totalRoutes: 0,
        totalDistance: 0,
        avgDuration: 0,
        avgCost: 0
    });

    // 获取路线数据 - 必须提供dataId
    const fetchRoutes = async (dataId) => {
        if (!dataId) {
            message.warning('请先选择批次');
            return;
        }

        try {
            setLoading(true);
            const response = await routesAPI.getByDataId(dataId);
            // response已经是data部分，确保是数组
            const data = Array.isArray(response) ? response : [];

            // 打印原始数据用于调试
            console.log('Raw routes data:', response);
            console.log('Processed routes data:', data);
            
            // 检查数据结构
            if (data.length > 0) {
                console.log('First route structure:', data[0]);
                if (data[0].nodes) {
                    console.log('First route nodes sample:', data[0].nodes.slice(0, 3));
                }
                if (data[0].node_details) {
                    console.log('First route node_details sample:', data[0].node_details.slice(0, 3));
                }
            }

            setRoutes(data);

            // 计算统计信息
            const stats = {
                totalRoutes: data.length,
                totalDistance: 0, // 后端没有总距离字段
                avgDuration: data.length > 0 ? data.reduce((sum, route) => sum + (route.total_travel_time || 0), 0) / data.length : 0,
                avgCost: data.length > 0 ? data.reduce((sum, route) => sum + (route.total_cost || 0), 0) / data.length : 0
            };
            setStatistics(stats);

            message.success(`路线数据加载成功，共${data.length}条路线`);
        } catch (error) {
            console.error('获取路线数据失败:', error);
            message.error('获取路线数据失败');
            setRoutes([]);
            setStatistics({
                totalRoutes: 0,
                totalDistance: 0,
                avgDuration: 0,
                avgCost: 0
            });
        } finally {
            setLoading(false);
        }
    };

    // 处理路线选择
    const handleRouteSelect = (route) => {
        console.log('Selected route:', route); // 添加调试日志
        setSelectedRoute(route);
    };

    // 加载批次列表
    const loadBatchList = useCallback(async () => {
        try {
            const response = await uploadDataAPI.getBatchList(1, 100); // 获取前100个批次
            setBatchList(response.records || []);
        } catch (error) {
            console.error('加载批次列表失败:', error);
        }
    }, []);

    // 处理批次选择
    const handleBatchSelect = (value) => {
        setDataId(value);
        if (value) {
            fetchRoutes(value);
        }
    };

    // 处理手动输入dataId
    const handleSearch = () => {
        if (dataId) {
            fetchRoutes(dataId);
        }
    };

    // 处理路线刷新
    const handleRefresh = async () => {
        if (dataId) {
            await fetchRoutes(dataId);
        }
    };

    // 切换视图模式
    const handleViewModeChange = (mode) => {
        setViewMode(mode);
    };

    // 处理数据导出
    const handleExport = () => {
        const data = routes.map(route => ({
            '路线ID': route.route_id,
            '起点': route.nodes && route.nodes.length > 0 ? (typeof route.nodes[0] === 'object' ? route.nodes[0].name : route.nodes[0]) : '-',
            '终点': route.nodes && route.nodes.length > 0 ? (typeof route.nodes[route.nodes.length - 1] === 'object' ? route.nodes[route.nodes.length - 1].name : route.nodes[route.nodes.length - 1]) : '-',
            '耗时': formatTime(route.travel_times),
            '成本': formatCurrency(route.total_cost),
            '容量': route.capacity,
            '剩余容量': route.remaining_capacity,
            '途经城市': route.nodes ? route.nodes.map(n => typeof n === 'object' ? n.name : n).join(', ') : '-',
            '创建时间': route.createTime ? new Date(route.createTime).toLocaleString() : '-'
        }));

        const csvContent = [
            Object.keys(data[0]).join(','),
            ...data.map(row => Object.values(row).join(','))
        ].join('\n');

        const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `routes_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();

        message.success('路线数据导出成功');
    };

    // 页面加载时获取批次列表
    useEffect(() => {
        loadBatchList();
    }, [loadBatchList]);

    // 使用 useEffect 监听 routes 变化并打印
    useEffect(() => {
        console.log('Routes updated:', routes);
    }, [routes]);

    // 表格列配置
    const columns = [
        {
            title: '路线ID',
            dataIndex: 'route_id',
            key: 'route_id',
            width: 80,
            render: (text) => <span style={{fontWeight: 500}}>{text || '-'}</span>,
            sorter: (a, b) => (a.route_id || 0) - (b.route_id || 0)
        },
        {
            title: '起点',
            dataIndex: 'nodes',
            key: 'origin',
            ellipsis: true,
            filter: true,
            render: (nodes) => nodes && nodes.length > 0 ? (typeof nodes[0] === 'object' ? nodes[0].name : nodes[0]) : '-'
        },
        {
            title: '终点',
            dataIndex: 'nodes',
            key: 'destination',
            ellipsis: true,
            filter: true,
            render: (nodes) => nodes && nodes.length > 0 ? (typeof nodes[nodes.length - 1] === 'object' ? nodes[nodes.length - 1].name : nodes[nodes.length - 1]) : '-'
        },
        {
            title: '耗时',
            dataIndex: 'total_travel_time',
            key: 'total_travel_time',
            width: 100,
            render: (duration) => formatTime(duration),
            sorter: (a, b) => (a.total_travel_time || 0) - (b.total_travel_time || 0)
        },
        {
            title: '成本',
            dataIndex: 'total_cost',
            key: 'total_cost',
            width: 100,
            render: (cost) => formatCurrency(cost),
            sorter: (a, b) => (a.total_cost || 0) - (b.total_cost || 0)
        },
        {
            title: '容量',
            dataIndex: 'capacity',
            key: 'capacity',
            width: 80,
            sorter: (a, b) => (a.capacity || 0) - (b.capacity || 0)
        },
        {
            title: '剩余容量',
            dataIndex: 'remaining_capacity',
            key: 'remaining_capacity',
            width: 100,
            sorter: (a, b) => (a.remaining_capacity || 0) - (b.remaining_capacity || 0)
        },
        {
            title: '途经城市',
            dataIndex: 'nodes',
            key: 'nodes',
            ellipsis: true,
            render: (waypoints) => {
                if (!waypoints || !Array.isArray(waypoints) || waypoints.length === 0) {
                    return '-';
                }
                return (
                    <Space size="small" wrap>
                        {waypoints.slice(0, 5).map((city, index) => (
                            <Tag key={index} color="blue">{typeof city === 'object' ? city.name : city}</Tag>
                        ))}
                        {waypoints.length > 5 && (
                            <Tag color="default">+{waypoints.length - 3}</Tag>
                        )}
                    </Space>
                );
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="link"
                        size="small"
                        icon={<AimOutlined/>}
                        onClick={() => handleRouteSelect(record)}
                    >
                        查看
                    </Button>
                </Space>
            )
        }
    ];

    return (
        <div className="routes-page">
            {/* 统计卡片 */}
            <Row gutter={16} style={{marginBottom: 24}}>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="总路线数"
                            value={statistics.totalRoutes}
                            prefix={<AimOutlined/>}
                            valueStyle={{color: '#1890ff'}}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="总距离"
                            value={statistics.totalDistance}
                            precision={1}
                            suffix="km"
                            valueStyle={{color: '#52c41a'}}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="平均耗时"
                            value={statistics.avgDuration}
                            precision={1}
                            suffix="小时"
                            valueStyle={{color: '#faad14'}}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="平均成本"
                            value={statistics.avgCost}
                            precision={2}
                            prefix="¥"
                            valueStyle={{color: '#f5222d'}}
                        />
                    </Card>
                </Col>
            </Row>

            {/* 工具栏 */}
            <Card style={{marginBottom: 24}}>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px'}}>
                    <h3 style={{margin: 0}}>路线管理</h3>
                    <Space wrap>
                        <Select
                            placeholder="选择批次"
                            value={dataId}
                            onChange={handleBatchSelect}
                            style={{width: 200}}
                            size="small"
                            allowClear
                        >
                            {batchList.map(batch => (
                                <Option key={batch.dataId} value={batch.dataId}>
                                    批次{batch.dataId} - {batch.description || '无描述'}
                                </Option>
                            ))}
                        </Select>
                        <Input
                            placeholder="或输入批次ID"
                            value={dataId}
                            onChange={(e) => setDataId(e.target.value)}
                            onPressEnter={handleSearch}
                            style={{width: 120}}
                            size="small"
                        />
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={handleSearch}
                            loading={loading}
                            size="small"
                        >
                            查询
                        </Button>
                        <Button
                            type="primary"
                            icon={<ReloadOutlined/>}
                            onClick={handleRefresh}
                            loading={loading}
                            size="small"
                        >
                            刷新
                        </Button>
                        <Button
                            icon={<ExportOutlined/>}
                            onClick={handleExport}
                            disabled={routes.length === 0}
                            size="small"
                        >
                            导出
                        </Button>
                    </Space>
                </div>
            </Card>

            {/* 路线列表/地图和详情区域 */}
            <Row gutter={16}>
                <Col span={12}>
                    {viewMode === 'list' ? (
                        <Card
                            title="路线列表"
                            style={{height: '600px', overflow: 'auto'}}
                        >
                            <div style={{padding: '16px 0'}}>
                                {routes.length === 0 ? (
                                    <div style={{
                                        display: 'flex',
                                        flexDirection: 'column',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        height: '100%',
                                        textAlign: 'center'
                                    }}>
                                        <h3 style={{color: '#999'}}>暂无路线数据</h3>
                                    </div>
                                ) : (
                                    <div>
                                        <div style={{marginBottom: 16, color: '#666', fontSize: '12px'}}>
                                            共 {routes.length} 条路线，点击路线查看详情
                                        </div>
                                        <div style={{maxHeight: '500px', overflowY: 'auto'}}>
                                            {routes.map(route => (
                                                <Card
                                                    key={route.id}
                                                    size="small"
                                                    hoverable
                                                    style={{
                                                        marginBottom: 8,
                                                        borderColor: selectedRoute?.id === route.id ? '#1890ff' : '#d9d9d9',
                                                        backgroundColor: selectedRoute?.id === route.id ? '#e6f7ff' : '#fff',
                                                        cursor: 'pointer'
                                                    }}
                                                    onClick={() => handleRouteSelect(route)}
                                                >
                                                    <div style={{padding: '4px 8px'}}>
                                                        <div style={{
                                                            display: 'flex',
                                                            justifyContent: 'space-between',
                                                            alignItems: 'center'
                                                        }}>
                                                            <strong>路线 #{route.route_id}</strong>
                                                            <Tag color="blue" size="small">
                                                                {route.capacity || 0} 容量
                                                            </Tag>
                                                        </div>
                                                        <div style={{marginTop: 8, fontSize: '13px', color: '#666'}}>
                                                            {route.nodes && route.nodes.length > 0 ? (
                                                                <span>
                                                                    {typeof route.nodes[0] === 'object' ? route.nodes[0].name : route.nodes[0]}
                                                                    {' → '}
                                                                    {typeof route.nodes[route.nodes.length - 1] === 'object'
                                                                        ? route.nodes[route.nodes.length - 1].name
                                                                        : route.nodes[route.nodes.length - 1]}
                                                                </span>
                                                            ) : (
                                                                <span style={{color: '#999'}}>无路线信息</span>
                                                            )}
                                                        </div>
                                                        <div style={{marginTop: 4, fontSize: '12px', color: '#999'}}>
                                                            共 {route.nodes ? route.nodes.length : 0} 个城市
                                                        </div>
                                                    </div>
                                                </Card>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </div>
                        </Card>
                    ) : (
                        <Card
                            title="路线地图"
                            styles={{body: {padding: 0}}}
                            style={{height: '600px'}}
                        >
                            <MapViewer
                                mode="routes"
                                routes={routes}
                                onRouteClick={handleRouteSelect}
                                height="100%"
                            />
                        </Card>
                    )}
                </Col>

                <Col span={12}>
                    {selectedRoute ? (
                        <Card
                            title="路线详情"
                            extra={
                                <Button
                                    type="text"
                                    onClick={() => setSelectedRoute(null)}
                                >
                                    关闭
                                </Button>
                            }
                            style={{height: '600px', overflow: 'auto'}}
                        >
                            <div style={{padding: '16px 0'}}>
                                {/* 基本信息卡片 */}
                                <Card size="small" style={{marginBottom: 16}}>
                                    <Row gutter={16}>
                                        <Col span={12}>
                                            <div style={{textAlign: 'center'}}>
                                                <div style={{color: '#1890ff', fontWeight: 'bold', fontSize: '18px'}}>
                                                    {selectedRoute.nodes && selectedRoute.nodes.length > 0
                                                        ? (typeof selectedRoute.nodes[0] === 'object' ? selectedRoute.nodes[0].name : selectedRoute.nodes[0])
                                                        : '-'}
                                                </div>
                                                <div style={{fontSize: '12px', color: '#666'}}>起点城市</div>
                                            </div>
                                        </Col>
                                        <Col span={12}>
                                            <div style={{textAlign: 'center'}}>
                                                <div style={{color: '#52c41a', fontWeight: 'bold', fontSize: '18px'}}>
                                                    {selectedRoute.nodes && selectedRoute.nodes.length > 0
                                                        ? (typeof selectedRoute.nodes[selectedRoute.nodes.length - 1] === 'object'
                                                            ? selectedRoute.nodes[selectedRoute.nodes.length - 1].name
                                                            : selectedRoute.nodes[selectedRoute.nodes.length - 1])
                                                        : '-'}
                                                </div>
                                                <div style={{fontSize: '12px', color: '#666'}}>终点城市</div>
                                            </div>
                                        </Col>
                                    </Row>
                                    <Row gutter={16} style={{marginTop: 16}}>
                                        <Col span={8}>
                                            <div style={{textAlign: 'center'}}>
                                                <div style={{color: '#fa8c16', fontWeight: 'bold', fontSize: '16px'}}>
                                                    {selectedRoute.capacity || 0}
                                                </div>
                                                <div style={{fontSize: '12px', color: '#666'}}>总容量</div>
                                            </div>
                                        </Col>
                                        <Col span={8}>
                                            <div style={{textAlign: 'center'}}>
                                                <div style={{color: '#722ed1', fontWeight: 'bold', fontSize: '16px'}}>
                                                    {formatTime(selectedRoute.total_travel_time)}
                                                </div>
                                                <div style={{fontSize: '12px', color: '#666'}}>总耗时</div>
                                            </div>
                                        </Col>
                                        <Col span={8}>
                                            <div style={{textAlign: 'center'}}>
                                                <div style={{color: '#eb2f96', fontWeight: 'bold', fontSize: '16px'}}>
                                                    {formatCurrency(selectedRoute.total_cost)}
                                                </div>
                                                <div style={{fontSize: '12px', color: '#666'}}>总成本</div>
                                            </div>
                                        </Col>
                                    </Row>
                                </Card>

                                {/* 分段详情 */}
                                <Card size="small" title="分段详情" style={{marginBottom: 16}}>
                                    {selectedRoute.nodes && selectedRoute.nodes.length > 1 && selectedRoute.costs && selectedRoute.travelTimes && (
                                        <div>
                                            {selectedRoute.nodes.slice(0, -1).map((fromCity, index) => {
                                                const toCity = selectedRoute.nodes[index + 1];
                                                const cost = selectedRoute.costs[index] || 0;
                                                const time = selectedRoute.travelTimes[index] || 0;
                                                const fromCityName = typeof fromCity === 'object' ? fromCity.name : fromCity;
                                                const toCityName = typeof toCity === 'object' ? toCity.name : toCity;
                                                return (
                                                    <Card key={index} size="small"
                                                          style={{marginBottom: 8, backgroundColor: '#f0f2f5'}}>
                                                        <Row gutter={16} align="middle">
                                                            <Col span={6}>
                                                                <div style={{textAlign: 'center'}}>
                                                                    <div style={{
                                                                        fontWeight: 'bold',
                                                                        color: '#1890ff'
                                                                    }}>{fromCityName}</div>
                                                                    <div style={{fontSize: '12px', color: '#666'}}>→
                                                                    </div>
                                                                    <div style={{
                                                                        fontWeight: 'bold',
                                                                        color: '#52c41a'
                                                                    }}>{toCityName}</div>
                                                                </div>
                                                            </Col>
                                                            <Col span={6}>
                                                                <div style={{textAlign: 'center'}}>
                                                                    <div style={{
                                                                        color: '#fa8c16',
                                                                        fontWeight: 'bold'
                                                                    }}>{formatCurrency(cost)}</div>
                                                                    <div
                                                                        style={{fontSize: '12px', color: '#666'}}>路段成本
                                                                    </div>
                                                                </div>
                                                            </Col>
                                                            <Col span={6}>
                                                                <div style={{textAlign: 'center'}}>
                                                                    <div style={{
                                                                        color: '#722ed1',
                                                                        fontWeight: 'bold'
                                                                    }}>{formatTime(time)}</div>
                                                                    <div
                                                                        style={{fontSize: '12px', color: '#666'}}>路段耗时
                                                                    </div>
                                                                </div>
                                                            </Col>
                                                            <Col span={6}>
                                                                <div style={{textAlign: 'center'}}>
                                                                    <Tag color="blue">路段 {index + 1}</Tag>
                                                                </div>
                                                            </Col>
                                                        </Row>
                                                    </Card>
                                                );
                                            })}
                                        </div>
                                    )}
                                </Card>

                                {/* 途经城市 */}
                                <Card size="small" title="途经城市">
                                    <div style={{marginTop: 8}}>
                                        <Space size="small" wrap>
                                            {selectedRoute.nodes && selectedRoute.nodes.map((city, index) => (
                                                <Tag key={index} color={ROUTE_COLORS[index % ROUTE_COLORS.length]}>
                                                    {typeof city === 'object' ? city.name : city}
                                                </Tag>
                                            ))}
                                        </Space>
                                    </div>
                                    <div style={{marginTop: 8, fontSize: '12px', color: '#666'}}>
                                        共 {selectedRoute.nodes ? selectedRoute.nodes.length : 0} 个城市
                                    </div>
                                </Card>
                            </div>
                        </Card>
                    ) : (
                        <Card
                            title="路线信息"
                            style={{height: '600px'}}
                        >
                            <div style={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                height: '100%',
                                textAlign: 'center'
                            }}>
                                <AimOutlined style={{fontSize: 48, color: '#ccc', marginBottom: 16}}/>
                                <h3>选择路线查看详情</h3>
                                <p style={{color: '#999'}}>点击左侧地图上的路线或下方表格中的"查看"按钮</p>
                            </div>
                        </Card>
                    )}
                </Col>
            </Row>

            {/* 数据表格 */}
            <Card style={{marginTop: 24}}>
                <DataTable
                    title="路线列表"
                    data={routes}
                    columns={columns}
                    loading={loading}
                    exportable
                    searchable
                    pagination
                    rowKey="id"
                    style={{marginTop: 16}}
                />
            </Card>
        </div>
    );
};

export default RoutesPage;